using B.S.XZYData.Api.Read.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace B.S.XZYData.Api.Read.Application.Handler.Process
{
    /// <summary>
    /// 根据工序Id查询工序采集数据处理器
    /// </summary>
    public class QueryProcessCollectionDataHandler : IRequestHandler<QueryProcessCollectionDataCommand, ApiResult<List<ProcessCollectionDataDto>>>
    {
        private readonly IBaseRepository<ProcessCollectionData> _collectionDataRepo;
        private readonly ILogger<QueryProcessCollectionDataHandler> _logger;

        public QueryProcessCollectionDataHandler(
            IBaseRepository<ProcessCollectionData> collectionDataRepo,
            ILogger<QueryProcessCollectionDataHandler> logger)
        {
            _collectionDataRepo = collectionDataRepo;
            _logger = logger;
        }

        public async Task<ApiResult<List<ProcessCollectionDataDto>>> Handle(QueryProcessCollectionDataCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<ProcessCollectionDataDto>>();
            try
            {
                // 查询指定工序的采集数据
                var collectionDataList = _collectionDataRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessId == request.ProcessId)
                    .OrderBy(x => x.CreatorDate)
                    .ToList();

                // 转换为DTO
                var dtoList = collectionDataList.Select(x => new ProcessCollectionDataDto
                {
                    Id = x.Id,
                    ProcessId = x.ProcessId,
                    DataType = x.DataType,
                    DataName = x.DataName,
                    CreatorDate = x.CreatorDate,
                    Creator = x.Creator,
                    UpdatorDate = x.UpdatorDate,
                    Updator = x.Updator
                }).ToList();

                res.Data = dtoList;
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询工序采集数据异常：{ex.Message}");
                res.Msg = "查询工序采集数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 